package cn.fufeiii.bt.threadpool;

import cn.hutool.core.thread.NamedThreadFactory;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author FuFei
 */
public class ThreadPoolMain {

    public static void main(String[] args) throws InterruptedException {

        ExecutorService threadPoolExecutor = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS,
                new RetryLinkedBlockingQueue<>(1, new RetryLinkedBlockingQueue.RetryConfig(3, 1, TimeUnit.SECONDS)),
                new NamedThreadFactory("", false),
                new ThreadPoolExecutor.CallerRunsPolicy());

        int cycleCount = 10;
        CountDownLatch countDownLatch = new CountDownLatch(cycleCount);
        for (int i = 1; i <= cycleCount; i++) {
            AtomicInteger atomicInteger = new AtomicInteger(i);
            threadPoolExecutor.execute(new Runnable() {
                private final Integer id = atomicInteger.get();

                @Override
                public void run() {
                    System.out.println("当前是第" + id + "个：" + Thread.currentThread().getName());
                    try {
                        TimeUnit.SECONDS.sleep(1);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

                @Override
                public String toString() {
                    return "元素ID" + id;
                }
            });
            countDownLatch.countDown();
        }
        countDownLatch.await();
        threadPoolExecutor.shutdown();
    }


}